//
//  SearchViewController.m
//  BTRIP
//
//  Created by Rain on 15/11/19.
//  Copyright © 2015年 johnbk. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchSceneryCollectionViewCell.h"
#import "SearchTravelTableViewCell.h"
#import "DataHandle.h"
#import "SearchModel.h"
#import "SearchOtherModel.h"
#import "FirstDetailTravelViewController.h"
#import "SpecialDetailViewController.h"

@interface SearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, retain) UISegmentedControl *segmentedControl;

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) UIScrollView *scrollView;

@property (nonatomic, retain) NSMutableArray *modelArr;

@property (nonatomic, retain) NSMutableArray *modelOtherArr;

@property (nonatomic, retain) UIButton *button;

@end

@implementation SearchViewController

- (void)dealloc {
    [_segmentedControl release];
    [_scrollView release];
    [_tableView release];
    [_searchBar release];
    [_collectionView release];
    [_modelArr release];
    [_modelOtherArr release];
    
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"搜索";
    self.modelArr = [NSMutableArray array];
    self.modelOtherArr = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createSearch];
    
    [self createUI];
    
}


- (void)dataload_Search:(NSString *)url {
    
    NSString *urlStr = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [DataHandle contectWithURL:urlStr andParameters:nil andViewController:self andBlock:^(id response) {
        for (NSDictionary *tempDic in response) {
            SearchModel *model = [[SearchModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            
            [self.modelArr addObject:model];
            
        }
        if (self.modelArr.count == 0) {
            //提示框
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"无搜索结果" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:alertAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
        [self.tableView reloadData];
    }];
}

- (void)dataload_SearchOther:(NSString *)url {
    
    NSString *urlStr = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [DataHandle contectWithURL:urlStr andParameters:nil andViewController:self andBlock:^(id response) {
        for (NSDictionary *tempDic in response) {
            SearchOtherModel *model = [[SearchOtherModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            
            [self.modelOtherArr addObject:model];
            
        }
        [self.collectionView reloadData];
    }];
}

- (void)createSearch {
    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64 * SWIDTH, KWIDTH, 40 * SWIDTH)];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入国家或城市";
    [self.view addSubview:self.searchBar];
    [self.searchBar release];
    
    
}

- (void)createUI {
    
//    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"游记", @"旅行地"]];
//    self.segmentedControl.frame = CGRectMake(10 * SWIDTH, 104 * SWIDTH, KWIDTH - 20 * SWIDTH, 30 * SWIDTH);
//    self.segmentedControl.selectedSegmentIndex = 0;
//    self.segmentedControl.backgroundColor = [UIColor whiteColor];
//    self.segmentedControl.tintColor = [UIColor lightGrayColor];
    
//    self.segmentedControl.tintColor = [UIColor clearColor];
//    NSDictionary *selectedTextAttribute = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:[UIColor redColor]};
//    [self.segmentedControl setTitleTextAttributes:selectedTextAttribute forState:UIControlStateSelected];
//    NSDictionary *unSelectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:[UIColor blackColor]};
//    [self.segmentedControl setTitleTextAttributes:unSelectedTextAttributes forState:UIControlStateNormal];
    
    [self.segmentedControl addTarget:self action:@selector(selectedSegmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
    [self.segmentedControl release];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 104 * SWIDTH, KWIDTH, KHEIGHT - 104 * SWIDTH)];
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(KWIDTH * 2, KHEIGHT - 104 * SWIDTH);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = YES;
    [self.view addSubview:self.scrollView];
    [self.scrollView release];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT - 104 * SWIDTH) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.scrollView addSubview:self.tableView];
    [self.tableView release];
    
    [self.tableView registerClass:[SearchTravelTableViewCell class] forCellReuseIdentifier:@"searchTravelCell"];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((KWIDTH - 40) / 2, (KWIDTH - 40) / 3);
    flowLayout.minimumInteritemSpacing = 10 * SWIDTH;
    flowLayout.minimumLineSpacing = 10 * SWIDTH;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(KWIDTH, 0, KWIDTH, KHEIGHT - 104 * SWIDTH) collectionViewLayout:flowLayout];
    self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.collectionView];
    [self.collectionView release];
    
    [self.collectionView registerClass:[SearchSceneryCollectionViewCell class] forCellWithReuseIdentifier:@"searchSceneryCell"];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(10 * SWIDTH, 25 * SWIDTH, 30 * SWIDTH, 30 * SWIDTH);
//    [self.button setTitle:@"返回" forState:UIControlStateNormal];
//    [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.button setImage:[UIImage imageNamed:@"iconfont-fanhui-3"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.button];
//    [self.navigationItem.leftBarButtonItem release];
    
}

#pragma mark 返回单元格数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _modelOtherArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _modelArr.count;
}

#pragma mark 返回单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchTravelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchTravelCell" forIndexPath:indexPath];
    cell.travel = _modelArr[indexPath.row];
    return cell;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchSceneryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchSceneryCell" forIndexPath:indexPath];
    cell.searchModel = _modelOtherArr[indexPath.row];
    return cell;
    
}

#pragma mark 返回行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 240 * SWIDTH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FirstDetailTravelViewController *firstVC = [[FirstDetailTravelViewController alloc] init];
    firstVC.ID = [_modelArr[indexPath.row] ID];
    [self.navigationController pushViewController:firstVC animated:YES];
    [firstVC release];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SpecialDetailViewController *detailVC = [[SpecialDetailViewController alloc] init];
    detailVC.urlStr = [NSString stringWithFormat:@"http://chanyouji.com/api/articles/%@.json?page=1", [_modelOtherArr[indexPath.row] ID]];
    NSLog(@"%@", detailVC.urlStr);
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar setShowsCancelButton:NO animated:YES];
    [self.searchBar resignFirstResponder];
    
    [self.modelArr removeAllObjects];
    [self.modelOtherArr removeAllObjects];
    
    [self dataload_Search:[NSString stringWithFormat:@"http://chanyouji.com/api/search/trips.json?q=%@&page=1", self.searchBar.text]];
    [self dataload_SearchOther:[NSString stringWithFormat:@"http://chanyouji.com/api/search/attractions.json?q=%@&page=1", self.searchBar.text]];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    [self.searchBar setShowsCancelButton:YES animated:YES];
    return YES;
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
    
}

#pragma mark segmented事件
- (void)selectedSegmentAction:(UISegmentedControl *)segmented {
    self.scrollView.contentOffset = CGPointMake(self.segmentedControl.selectedSegmentIndex * KWIDTH, 0);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    self.segmentedControl.selectedSegmentIndex = self.scrollView.contentOffset.x / KWIDTH;
    
}

- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
